<?php
	//error_reporting(0);
	function number_format_cn($num) {
		$str = '';
		if ($num > 100000000) {
			$a = $num / 100000000;
			$num = $num % 100000000;
			$str .= floor($a).'亿';
		}
		if ($num > 10000) {
			$a = $num / 10000;
			$num = $num % 10000;
			$str .= round($a).'万';
		}
		return $str;
	}

	function OpenDB($str) {
		try {
			$mongodb = new Mongo($str);
		} catch(MongoConnectionException $e) {
			return array('status'=>'error','info'=>$e->getMessage());
		}
		return $mongodb;
	}

	function CloseDB($mongodb){
		$mongodb->close();
	}

	function GetCursorArray($cursor){
		$result = array();
		if ($cursor->count()){
			while($d = $cursor->getNext()){
				foreach ($d as $key => $value) {
					$r[$key] = $value;
				}
				$result[] = $r;
			}
		}
		return $result;
	}

	function GetCollections($sgk){
		$tables = array();
		$indexCollection = $sgk->SelectCollection("index");
		$cursor = $indexCollection->find();
		$re = GetCursorArray($cursor);
		foreach ($re as $key => $value) {
			$tables[] = array('table'=>$value['collection'],
				"username"=>$value["field"]['username'],
				"password"=>$value["field"]['password'],
				"excerpt"=>$value['excerpt'],
				);
		}
		return $tables;
	}

	/**
	 * [GetData4Collections 查询数据库条件]
	 * @param [type] $sgk         [库]
	 * @param [type] $collections [集合的名字列表，字段列表]
	 * @param [type] $condition   [条件]
	 */
	function GetData4Collections($sgk,$collections,$condition){
		$result = array();
		if (!$sgk) return $result;
		if (!$collections) return $result;
		if (!$condition) return $result;
		if (!is_array($collections)) return $result;
		if ($condition['type'] == 'like') {
			$my_cond = new MongoRegex('/'.$condition['str'].'/i');
		} else if ($condition['type']=='eq') {
			$my_cond = $condition['str'];
		}

		foreach ($collections as $value) {
			$collection = $sgk->SelectCollection($value['table']);
			$field = '';
			if ($condition['field'] == 'username') {
				$field = $value['username'];
				if (empty($field)) {
					$field = $value['email'];
				}
			} else if ($condition['field'] == 'email') {
				$field = $value['email'];
				if (empty($field)) {
					$field = $value['username'];
				}
			}
			if (empty($field)) {
				$result[$value['excerpt']] =array('info'=>'查询异常,没有绑定对应数据');
				continue;
			}
			$cond = array($field=>$my_cond);

	
			try{
				$cursor = $collection->find($cond,array('_id'=>0));
				while ($d = $cursor->getNext()) {
					$result[$value['excerpt']][] = $d;

					//print_r($d);
				}
			} catch(MongoCursorException $e) {
				$result[$value['excerpt']] =array('info'=>'查询异常'.$e->getMessage());
			}
		}
		return $result;
	}
